import os
import uuid
import subprocess
from pygame import mixer

def play_mp3_file(out_mp3, playback_speed):
    # 变速处理
    if abs(playback_speed - 1.0) > 0.01:
        temp_speed_mp3 = f"{uuid.uuid4().hex}_speed.mp3"
        atempo = playback_speed
        # ffmpeg atempo支持0.5-2.0，超出需分多次
        if 0.5 <= atempo <= 2.0:
            atempo_filter = f"atempo={atempo}"
        else:
            factors = []
            remain = atempo
            while remain > 2.0:
                factors.append(2.0)
                remain /= 2.0
            while remain < 0.5:
                factors.append(0.5)
                remain /= 0.5
            factors.append(remain)
            atempo_filter = ",".join([f"atempo={f:.3f}" for f in factors])
        cmd = [
            "ffmpeg", "-y", "-i", out_mp3, "-filter:a",
            atempo_filter, temp_speed_mp3
        ]
        subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        play_file = temp_speed_mp3
    else:
        play_file = out_mp3
    mixer.music.load(play_file)
    mixer.music.play()
    return play_file

def cleanup_speed_mp3():
    for fname in os.listdir('.'):
        if fname.endswith('_speed.mp3'):
            try:
                os.remove(fname)
            except Exception:
                pass
